/**
 * 茶叶资产管理系统 - 前端JavaScript
 */

// API基础URL
const API_BASE_URL = '/api/tea';

// 显示结果到结果区域
function showResult(result) {
    const resultArea = document.getElementById('resultArea');
    resultArea.innerHTML = ''; // 清空结果区域
    
    if (typeof result === 'string') {
        // 如果是纯文本消息，直接显示
        resultArea.textContent = result;
        return;
    }
    
    // 创建美观的结果展示
    if (result) {
        // 处理操作状态 - 仅对非查询操作显示成功/失败状态
        if ((result.code !== '0' || !result.data || !isQueryOperation()) && result.message) {
            const statusDiv = document.createElement('div');
            statusDiv.className = result.code === '0' ? 'alert alert-success' : 'alert alert-danger';
            statusDiv.innerHTML = `<strong>${result.code === '0' ? '✓ 操作成功' : '✗ 操作失败'}</strong>`;
            if (result.message) {
                statusDiv.innerHTML += `<p>${result.message}</p>`;
            }
            resultArea.appendChild(statusDiv);
        }
        
        // 处理资产详情数据
        if (result.data) {
            // 首先检查是否有returnABIObject或returnObject格式数据
            if (result.data.returnABIObject && Array.isArray(result.data.returnABIObject)) {
                // 处理ABI格式的返回数据
                renderABIObjectData(result.data.returnABIObject, resultArea);
            } else if (result.data.returnObject && Array.isArray(result.data.returnObject)) {
                // 处理普通对象格式的返回数据
                renderObjectData(result.data.returnObject, resultArea);
            } else if (result.data.values && Array.isArray(result.data.values)) {
                // 处理资产状态信息
                if (result.stageInfo) {
                    const stageDiv = document.createElement('div');
                    stageDiv.className = 'card mb-3';
                    stageDiv.innerHTML = `
                        <div class="card-header bg-info text-white">
                            <strong>资产状态</strong>
                        </div>
                        <div class="card-body">
                            <h5 class="card-title">${result.stageInfo.name}</h5>
                            <p class="card-text">状态码: ${result.stageInfo.code}</p>
                        </div>
                    `;
                    resultArea.appendChild(stageDiv);
                }
                
                // 处理values数组数据
                try {
                    // 检查是否为单一状态值
                    if (result.data.values.length === 1 && !isNaN(parseInt(result.data.values[0]))) {
                        const stageCode = parseInt(result.data.values[0]);
                        renderStageInfo(stageCode, resultArea);
                    } else {
                        // 尝试作为茶叶资产详情处理
                        renderTeaAssetDetails(result.data.values, resultArea);
                    }
                } catch (e) {
                    // 解析失败，显示用户友好信息
                    showFriendlyErrorMessage(resultArea);
                }
            } else if (result.data.transactionHash) {
                // 交易类操作结果
                renderTransactionInfo(result.data, resultArea);
            } else {
                // 其他未知格式数据，显示友好提示
                showGenericSuccessMessage(result.data, resultArea);
            }
        }
    } else {
        resultArea.textContent = '未获取到任何结果数据';
    }
}

// 判断当前是否为查询操作
function isQueryOperation() {
    // 获取当前活动的表单或操作类型
    const detailsButton = document.getElementById('getDetailsBtn');
    
    // 检查查询按钮是否被最近点击过
    if (detailsButton && detailsButton.classList.contains('active')) {
        return true;
    }
    
    // 检查URL路径是否包含查询相关字符串
    const currentPath = window.location.pathname;
    if (currentPath.includes('/details')) {
        return true;
    }
    
    return false;
}

// 渲染ABI对象格式的数据
function renderABIObjectData(abiObjects, container) {
    const detailsDiv = document.createElement('div');
    detailsDiv.className = 'card';
    
    let detailsContent = '<div class="card-header bg-primary text-white"><strong>茶叶资产详情</strong></div>';
    detailsContent += '<div class="card-body"><table class="table table-striped"><tbody>';
    
    // 字段标签映射
    const fieldLabels = {
        'teaType': '茶叶类型',
        'origin': '产地',
        'harvestTime': '采摘时间',
        'processingInfo': '加工信息',
        'qualityReport': '质量报告',
        'currentOwner': '当前所有者'
    };
    
    // 状态名称映射
    const stageNames = ['新创建', '加工中', '质检通过', '运输中', '已售出'];
    
    // 遍历ABI对象
    abiObjects.forEach(obj => {
        let displayValue = '未知';
        
        // 跳过批次ID字段和状态字段
        if (obj.name === 'batchId' || obj.name === 'stage') {
            return;
        }
        
        if (obj.name && fieldLabels[obj.name]) {
            // 根据类型处理显示值
            if (obj.valueType === 'STRING' && obj.stringValue && obj.stringValue.value) {
                displayValue = obj.stringValue.value;
            } else if (obj.valueType === 'UINT' && obj.numericValue) {
                if (obj.name === 'harvestTime') {
                    // 转换时间戳为日期
                    try {
                        const date = new Date(Number(obj.numericValue.value));
                        displayValue = date.toLocaleString('zh-CN');
                    } catch (e) {
                        displayValue = obj.numericValue.value;
                    }
                } else {
                    displayValue = obj.numericValue.value;
                }
            } else if (obj.valueType === 'ADDRESS' && obj.addressValue) {
                displayValue = obj.addressValue.value;
            } else if (obj.valueType === 'BYTES' && obj.bytesValue) {
                // 显示批次ID的简短版本
                const fullId = obj.bytesValue.value;
                displayValue = fullId.substring(0, 10) + '...' + fullId.substring(fullId.length - 6);
            }
            
            detailsContent += `<tr><th>${fieldLabels[obj.name]}</th><td>${displayValue}</td></tr>`;
        }
    });
    
    detailsContent += '</tbody></table></div>';
    detailsDiv.innerHTML = detailsContent;
    container.appendChild(detailsDiv);
}

// 渲染普通对象格式的数据
function renderObjectData(objectData, container) {
    const detailsDiv = document.createElement('div');
    detailsDiv.className = 'card';
    
    let detailsContent = '<div class="card-header bg-primary text-white"><strong>茶叶资产详情</strong></div>';
    detailsContent += '<div class="card-body"><table class="table table-striped"><tbody>';
    
    // 查询结果字段映射（移除了批次ID和状态字段）
    const fieldLabels = [
        '茶叶类型', 
        '产地', 
        '采摘时间', 
        '加工信息', 
        '质量报告', 
        '当前所有者'
    ];
    
    // 遍历数据数组，跳过第一个元素（批次ID）和最后一个元素（状态）
    for (let i = 1; i < Math.min(objectData.length - 1, fieldLabels.length + 1); i++) {
        let value = objectData[i] || '-';
        
        // 特殊处理某些字段
        if (i === 3) { // 采摘时间
            try {
                const timestamp = Number(value);
                if (!isNaN(timestamp)) {
                    const date = new Date(timestamp);
                    value = date.toLocaleString('zh-CN');
                }
            } catch (e) {}
        }
        
        detailsContent += `<tr><th>${fieldLabels[i-1]}</th><td>${value}</td></tr>`;
    }
    
    detailsContent += '</tbody></table></div>';
    detailsDiv.innerHTML = detailsContent;
    container.appendChild(detailsDiv);
}

// 渲染茶叶资产详情
function renderTeaAssetDetails(valuesData, container) {
    const detailsDiv = document.createElement('div');
    detailsDiv.className = 'card';
    
    let detailsContent = '<div class="card-header bg-primary text-white"><strong>茶叶资产详情</strong></div>';
    detailsContent += '<div class="card-body"><table class="table table-striped"><tbody>';
    
    // 查询结果字段映射（移除了批次ID和状态字段）
    const fieldLabels = [
        '茶叶类型', 
        '产地', 
        '采摘时间', 
        '加工信息', 
        '质量报告', 
        '当前所有者'
    ];
    
    if (valuesData.length >= 8) {
        // 跳过第一个元素（批次ID）和最后一个元素（状态）
        for (let i = 1; i < Math.min(valuesData.length - 1, fieldLabels.length + 1); i++) {
            let value = valuesData[i] || '-';
            
            // 格式化处理特定字段
            if (i === 3 && value && value !== '-') { // 采摘时间
                try {
                    const timestamp = parseInt(value);
                    if (!isNaN(timestamp)) {
                        const date = new Date(timestamp);
                        value = date.toLocaleString('zh-CN');
                    }
                } catch (e) {}
            }
            
            detailsContent += `<tr><th>${fieldLabels[i-1]}</th><td>${value}</td></tr>`;
        }
    } else {
        // 一般性数据展示，小于8个字段时的处理
        valuesData.forEach((value, index) => {
            if ((index > 0 && index < valuesData.length - 1) || valuesData.length < 8) {
                const label = index < fieldLabels.length + 1 && valuesData.length >= 8 ? 
                    fieldLabels[index-1] : `数据 ${index}`;
                detailsContent += `<tr><th>${label}</th><td>${value}</td></tr>`;
            }
        });
    }
    
    detailsContent += '</tbody></table></div>';
    detailsDiv.innerHTML = detailsContent;
    container.appendChild(detailsDiv);
}

// 渲染状态信息
function renderStageInfo(stageCode, container) {
    const stageNames = ['新创建', '加工中', '质检通过', '运输中', '已售出'];
    const stageName = stageNames[stageCode] || '未知状态';
    
    const stageDiv = document.createElement('div');
    stageDiv.className = 'card';
    stageDiv.innerHTML = `
        <div class="card-header bg-info text-white">
            <strong>资产状态</strong>
        </div>
        <div class="card-body">
            <table class="table table-sm">
                <tbody>
                    <tr><th>当前状态</th><td>${stageName} (${stageCode})</td></tr>
                </tbody>
            </table>
        </div>
    `;
    container.appendChild(stageDiv);
}

// 渲染交易信息
function renderTransactionInfo(txData, container) {
    const txDiv = document.createElement('div');
    txDiv.className = 'card mt-3';
    txDiv.innerHTML = `
        <div class="card-header bg-secondary text-white">
            <strong>区块链交易信息</strong>
        </div>
        <div class="card-body">
            <table class="table table-sm">
                <tbody>
                    <tr><th>交易编号</th><td><small>${txData.transactionHash ? txData.transactionHash.substring(0, 10) + '...' + txData.transactionHash.substring(txData.transactionHash.length - 8) : '-'}</small></td></tr>
                    <tr><th>区块高度</th><td>${txData.blockNumber || '-'}</td></tr>
                    <tr><th>交易状态</th><td>${txData.status ? '<span class="badge badge-success">成功</span>' : '<span class="badge badge-danger">失败</span>'}</td></tr>
                    <tr><th>事件类型</th><td><span class="badge badge-info">茶叶资产操作</span></td></tr>
                </tbody>
            </table>
            <div class="alert alert-light mt-2">
                <small>该交易已成功写入区块链，数据不可篡改且永久保存。</small>
            </div>
        </div>
    `;
    container.appendChild(txDiv);
}

// 显示友好的错误信息
function showFriendlyErrorMessage(container) {
    const dataDiv = document.createElement('div');
    dataDiv.className = 'alert alert-warning mt-3';
    dataDiv.innerHTML = '<strong>提示</strong><p>系统返回了复杂数据，但无法以友好方式展示。请联系系统管理员获取更多信息。</p>';
    container.appendChild(dataDiv);
}

// 显示一般成功信息
function showGenericSuccessMessage(data, container) {
    const summaryDiv = document.createElement('div');
    summaryDiv.className = 'alert alert-info mt-3';
    summaryDiv.innerHTML = '<strong>操作完成</strong><p>系统已处理您的请求并返回结果。</p>';
    
    if (data.status !== undefined) {
        const statusStr = data.status ? '成功' : '失败';
        const statusClass = data.status ? 'success' : 'danger';
        summaryDiv.innerHTML += `<p>操作状态: <span class="badge badge-${statusClass}">${statusStr}</span></p>`;
    }
    
    container.appendChild(summaryDiv);
}

// 错误处理
function handleError(error) {
    console.error('Error:', error);
    
    const resultArea = document.getElementById('resultArea');
    resultArea.innerHTML = '';
    
    const errorDiv = document.createElement('div');
    errorDiv.className = 'alert alert-danger';
    errorDiv.innerHTML = `<strong>✗ 错误</strong><p>${error.message || '未知错误'}</p>`;
    resultArea.appendChild(errorDiv);
}

// 将十六进制字符串转换为Base64编码
function formatBatchIdToBase64(batchId) {
    // 去除可能存在的0x前缀
    if (batchId.startsWith('0x')) {
        batchId = batchId.substring(2);
    }
    
    // 如果长度不足64个字符(32字节)，在前面补0
    while (batchId.length < 64) {
        batchId = '0' + batchId;
    }
    
    // 将十六进制字符串转换为字节数组
    const bytes = new Uint8Array(32);
    for (let i = 0; i < 32; i++) {
        const hexByte = batchId.substring(i * 2, i * 2 + 2);
        bytes[i] = parseInt(hexByte, 16);
    }
    
    // 转换为Base64
    let binary = '';
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}

/**
 * 显示操作结果消息
 * @param {string} message 消息内容
 * @param {boolean} isSuccess 是否成功
 */
function showMessage(message, isSuccess = true) {
    // 创建临时消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = isSuccess ? 'alert alert-success fixed-message' : 'alert alert-danger fixed-message';
    messageDiv.innerHTML = `<strong>${isSuccess ? '✓ 成功' : '✗ 失败'}</strong><p>${message}</p>`;
    messageDiv.style.position = 'fixed';
    messageDiv.style.top = '20px';
    messageDiv.style.right = '20px';
    messageDiv.style.zIndex = '9999';
    messageDiv.style.maxWidth = '400px';
    messageDiv.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    messageDiv.style.transition = 'opacity 0.5s ease-in-out';
    
    // 添加到页面
    document.body.appendChild(messageDiv);
    
    // 3秒后淡出
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        setTimeout(() => {
            messageDiv.remove();
        }, 500);
    }, 3000);
}

/**
 * 创建茶叶资产
 */
function createTeaAsset() {
    const batchIdHex = document.getElementById('batchId').value;
    const teaType = document.getElementById('teaType').value;
    const origin = document.getElementById('origin').value;
    
    if (!batchIdHex || !teaType || !origin) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'alert alert-info fixed-message';
    loadingMessage.innerHTML = '<strong>处理中</strong><p>正在创建茶叶资产...</p>';
    loadingMessage.style.position = 'fixed';
    loadingMessage.style.top = '20px';
    loadingMessage.style.right = '20px';
    loadingMessage.style.zIndex = '9999';
    loadingMessage.style.maxWidth = '400px';
    loadingMessage.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    
    document.body.appendChild(loadingMessage);
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _teaType: teaType,
        _origin: origin
    };
    
    fetch(`${API_BASE_URL}/create`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 处理结果
        if (result.code === '0') {
            showMessage('茶叶资产创建成功！批次ID已记录在区块链上', true);
            
            // 可选：在创建成功后自动复制批次ID到所有表单
            // copyBatchIdToAll(batchIdHex);
        } else {
            let errorMsg = result.message || '未知错误';
            
            // 检查是否包含错误信息
            if (result.data && result.data.receiptMessages) {
                errorMsg = result.data.receiptMessages;
            }
            
            showMessage(`创建失败: ${errorMsg}`, false);
        }
    })
    .catch(error => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误
        showMessage(`发生错误: ${error.message || '未知错误'}`, false);
    });
}

/**
 * 获取茶叶资产详情
 */
function getTeaAssetDetails() {
    const batchIdHex = document.getElementById('queryBatchId').value;
    
    if (!batchIdHex) {
        // 使用原生alert替代showResult
        alert('错误: 批次ID是必填的!');
        return;
    }
    
    // 显示本地加载提示
    const detailsContainer = document.getElementById('assetDetailsContainer');
    detailsContainer.innerHTML = '<div class="alert alert-info">正在查询茶叶资产信息...</div>';
    detailsContainer.style.display = 'block';
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    // 标记查询按钮为活动状态
    const detailsButton = document.getElementById('getDetailsBtn');
    if (detailsButton) {
        detailsButton.classList.add('active');
    }
    
    fetch(`${API_BASE_URL}/details?batchId=${encodeURIComponent(batchId)}`)
    .then(response => response.json())
    .then(result => {
        if (result.code === '0') {
            // 成功获取数据，直接显示表格
            showTeaAssetDetailsTable(result);
            
            // 可选：在表格上方显示成功提示
            const successAlert = document.createElement('div');
            successAlert.className = 'alert alert-success mb-3';
            successAlert.innerHTML = '<strong>✓ 查询成功</strong><p>茶叶资产详情已显示在下方</p>';
            detailsContainer.insertBefore(successAlert, detailsContainer.firstChild);
            
            // 2秒后淡出成功提示
            setTimeout(() => {
                successAlert.style.transition = 'opacity 0.5s';
                successAlert.style.opacity = '0';
                setTimeout(() => successAlert.remove(), 500);
            }, 2000);
        } else {
            // 查询失败，显示错误信息
            detailsContainer.innerHTML = '';
            const errorDiv = document.createElement('div');
            errorDiv.className = 'alert alert-danger';
            errorDiv.innerHTML = `<strong>✗ 查询失败</strong><p>${result.message || '未知错误'}</p>`;
            detailsContainer.appendChild(errorDiv);
            detailsContainer.style.display = 'block';
        }
        
        // 重置按钮状态
        if (detailsButton) {
            setTimeout(() => {
                detailsButton.classList.remove('active');
            }, 100);
        }
    })
    .catch(error => {
        // 处理错误
        console.error('Error:', error);
        
        detailsContainer.innerHTML = '';
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger';
        errorDiv.innerHTML = `<strong>✗ 错误</strong><p>${error.message || '未知错误'}</p>`;
        detailsContainer.appendChild(errorDiv);
        detailsContainer.style.display = 'block';
    });
}

/**
 * 以表格形式展示茶叶资产详情
 */
function showTeaAssetDetailsTable(result) {
    // 获取专用于显示资产详情的容器
    const detailsContainer = document.getElementById('assetDetailsContainer');
    detailsContainer.innerHTML = ''; // 清空详情区域
    detailsContainer.style.display = 'block'; // 显示详情区域
    
    if (!result || !result.data || result.code !== '0') {
        // 处理错误情况
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger animated fadeIn';
        errorDiv.textContent = result?.message || '查询失败，请检查批次ID是否正确';
        detailsContainer.appendChild(errorDiv);
        return;
    }
    
    // 创建表格容器，添加淡入动画
    const tableContainer = document.createElement('div');
    tableContainer.className = 'tea-asset-details animated fadeIn';
    tableContainer.style.boxShadow = '0 8px 16px rgba(0, 0, 0, 0.1)';
    tableContainer.style.borderRadius = '8px';
    tableContainer.style.overflow = 'hidden';
    tableContainer.style.animation = 'fadeIn 0.5s ease-in-out';
    
    // 添加CSS动画
    const styleElement = document.createElement('style');
    styleElement.textContent = `
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes pulseHighlight {
            0% { box-shadow: 0 0 0 0 rgba(58, 140, 95, 0.7); }
            70% { box-shadow: 0 0 0 6px rgba(58, 140, 95, 0); }
            100% { box-shadow: 0 0 0 0 rgba(58, 140, 95, 0); }
        }
        
        .tea-asset-row:hover {
            background-color: #f9f9f9;
            transition: all 0.2s ease;
        }
        
        .animated {
            animation-duration: 0.5s;
            animation-fill-mode: both;
        }
        
        .fadeIn {
            animation-name: fadeIn;
        }
        
        .active-stage {
            animation: pulseHighlight 2s infinite;
        }
    `;
    document.head.appendChild(styleElement);
    
    // 创建卡片标题
    const titleDiv = document.createElement('div');
    titleDiv.className = 'card-header';
    titleDiv.style.background = 'linear-gradient(135deg, #3a8c5f 0%, #2a6d45 100%)';
    titleDiv.style.color = 'white';
    titleDiv.style.padding = '15px 20px';
    titleDiv.style.fontSize = '1.2rem';
    titleDiv.style.fontWeight = 'bold';
    titleDiv.innerHTML = '<i class="fa fa-leaf" style="margin-right: 8px;"></i>茶叶资产溯源详情';
    tableContainer.appendChild(titleDiv);
    
    // 创建表格
    const table = document.createElement('table');
    table.className = 'table table-striped table-bordered';
    table.style.marginBottom = '0';
    table.style.backgroundColor = 'white';
    
    // 直接创建表体，不使用表头
    const tbody = document.createElement('tbody');
    
    // 获取数据
    let assetData;
    let stageDesc = '';
    
    if (result.data.originData && Array.isArray(result.data.originData)) {
        assetData = result.data.originData;
        stageDesc = result.data.stageDesc || '未知状态';
    } else if (result.data.returnObject && Array.isArray(result.data.returnObject)) {
        assetData = result.data.returnObject;
        // 尝试从状态码获取状态描述
        const stageCode = assetData[7];
        stageDesc = getStageDescription(stageCode);
    } else {
        // 数据格式不符合预期
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-warning animated fadeIn';
        errorDiv.textContent = '无法解析返回的数据格式';
        detailsContainer.appendChild(errorDiv);
        return;
    }
    
    // 定义字段映射（已移除批次ID和状态码）
    const fieldLabels = [
        '茶叶类型', 
        '产地', 
        '采摘时间', 
        '加工信息', 
        '质量报告', 
        '当前所有者'
    ];
    
    // 为每个字段定义图标
    const fieldIcons = [
        'fa-leaf',         // 茶叶类型
        'fa-map-marker',   // 产地
        'fa-calendar',     // 采摘时间
        'fa-cogs',         // 加工信息
        'fa-clipboard',    // 质量报告
        'fa-user'          // 当前所有者
    ];
    
    // 添加数据行（跳过批次ID和状态码）
    // 茶叶类型的索引为1
    for (let i = 1; i < 7; i++) {
        const row = document.createElement('tr');
        row.className = 'tea-asset-row';
        row.style.transition = 'all 0.2s ease';
        
        // 添加动画延迟，创建级联效果
        row.style.animationDelay = `${(i-1) * 0.05}s`;
        
        // 属性名称
        const labelCell = document.createElement('td');
        labelCell.style.width = '30%';
        labelCell.style.fontWeight = 'bold';
        labelCell.style.padding = '12px 15px';
        labelCell.style.backgroundColor = '#f8f9fa';
        
        // 添加图标
        const iconSpan = document.createElement('span');
        iconSpan.className = `fa ${fieldIcons[i-1]}`;
        iconSpan.style.marginRight = '8px';
        iconSpan.style.color = '#3a8c5f';
        labelCell.appendChild(iconSpan);
        
        // 添加文本
        const textSpan = document.createElement('span');
        textSpan.textContent = fieldLabels[i-1];
        labelCell.appendChild(textSpan);
        
        row.appendChild(labelCell);
        
        // 属性值
        const valueCell = document.createElement('td');
        valueCell.style.padding = '12px 15px';
        let value = assetData[i] || '-';
        
        // 特殊处理采摘时间
        if (i === 3) { // 采摘时间
            try {
                const timestamp = Number(value);
                if (!isNaN(timestamp)) {
                    const date = new Date(timestamp);
                    value = date.toLocaleString('zh-CN');
                }
            } catch (e) {}
        }
        
        valueCell.textContent = value;
        row.appendChild(valueCell);
        
        tbody.appendChild(row);
    }
    
    // 添加状态行
    const stageRow = document.createElement('tr');
    stageRow.className = 'tea-asset-row state-row';
    stageRow.style.borderTop = '2px solid #dee2e6';
    stageRow.style.background = '#f8fcfa';
    
    const stageLabelCell = document.createElement('td');
    stageLabelCell.style.fontWeight = 'bold';
    stageLabelCell.style.padding = '15px';
    stageLabelCell.style.color = '#3a8c5f';
    
    // 添加状态图标
    const stageIconSpan = document.createElement('span');
    stageIconSpan.className = 'fa fa-tasks';
    stageIconSpan.style.marginRight = '8px';
    stageIconSpan.style.color = '#3a8c5f';
    stageLabelCell.appendChild(stageIconSpan);
    
    // 添加文本
    const stageTextSpan = document.createElement('span');
    stageTextSpan.textContent = '当前状态';
    stageLabelCell.appendChild(stageTextSpan);
    
    stageRow.appendChild(stageLabelCell);
    
    // 创建状态指示器容器
    const stageValueCell = document.createElement('td');
    stageValueCell.style.padding = '15px';
    
    // 获取状态码
    let stageCode = 0;
    if (result.data.originData && Array.isArray(result.data.originData) && result.data.originData.length >= 8) {
        stageCode = Number(result.data.originData[7]);
    } else if (result.data.returnObject && Array.isArray(result.data.returnObject) && result.data.returnObject.length >= 8) {
        stageCode = Number(result.data.returnObject[7]);
    }
    
    // 创建进度条容器
    const progressContainer = document.createElement('div');
    progressContainer.style.position = 'relative';
    progressContainer.style.marginBottom = '15px';
    progressContainer.style.height = '4px';
    progressContainer.style.backgroundColor = '#e9ecef';
    progressContainer.style.borderRadius = '4px';
    progressContainer.style.overflow = 'hidden';
    
    // 创建进度条
    const progressBar = document.createElement('div');
    progressBar.style.position = 'absolute';
    progressBar.style.top = '0';
    progressBar.style.left = '0';
    progressBar.style.height = '100%';
    progressBar.style.backgroundColor = '#3a8c5f';
    progressBar.style.borderRadius = '4px';
    progressBar.style.transition = 'width 1s ease';
    
    // 根据状态码计算进度百分比
    const totalStages = 5; // 从0到4共5个状态
    const progressPercent = (stageCode / (totalStages - 1)) * 100;
    progressBar.style.width = `${progressPercent}%`;
    
    progressContainer.appendChild(progressBar);
    stageValueCell.appendChild(progressContainer);
    
    // 创建状态指示器
    const stagesContainer = document.createElement('div');
    stagesContainer.className = 'tea-stages';
    stagesContainer.style.display = 'flex';
    stagesContainer.style.justifyContent = 'space-between';
    stagesContainer.style.alignItems = 'center';
    stagesContainer.style.position = 'relative';
    
    // 定义所有状态
    const allStages = [
        { code: 0, name: '已创建' },
        { code: 1, name: '正在加工' },
        { code: 2, name: '质检通过' },
        { code: 3, name: '运输中' },
        { code: 4, name: '已售出' }
    ];
    
    // 创建状态节点和连接线
    allStages.forEach((stage, index) => {
        const stageItem = document.createElement('div');
        stageItem.style.display = 'flex';
        stageItem.style.flexDirection = 'column';
        stageItem.style.alignItems = 'center';
        stageItem.style.position = 'relative';
        stageItem.style.flex = '1';
        
        // 创建状态节点
        const stageNode = document.createElement('div');
        stageNode.style.width = '16px';
        stageNode.style.height = '16px';
        stageNode.style.borderRadius = '50%';
        stageNode.style.marginBottom = '8px';
        stageNode.style.zIndex = '2';
        stageNode.style.transition = 'all 0.3s ease';
        
        // 当前状态和已完成状态的样式
        if (stage.code === stageCode) {
            stageNode.style.backgroundColor = '#3a8c5f';
            stageNode.style.boxShadow = '0 0 0 4px rgba(58, 140, 95, 0.2)';
            stageNode.className = 'active-stage';
        } else if (stage.code < stageCode) {
            stageNode.style.backgroundColor = '#3a8c5f';
        } else {
            stageNode.style.backgroundColor = '#dee2e6';
            stageNode.style.border = '1px solid #ced4da';
        }
        
        stageItem.appendChild(stageNode);
        
        // 创建状态文本
        const stageText = document.createElement('div');
        stageText.textContent = stage.name;
        stageText.style.fontSize = '0.8rem';
        stageText.style.fontWeight = stage.code === stageCode ? 'bold' : 'normal';
        stageText.style.color = stage.code === stageCode ? '#3a8c5f' : '#6c757d';
        stageText.style.textAlign = 'center';
        stageItem.appendChild(stageText);
        
        stagesContainer.appendChild(stageItem);
    });
    
    stageValueCell.appendChild(stagesContainer);
    stageRow.appendChild(stageValueCell);
    
    tbody.appendChild(stageRow);
    
    table.appendChild(tbody);
    tableContainer.appendChild(table);
    detailsContainer.appendChild(tableContainer);
}

/**
 * 根据状态码获取状态描述
 */
function getStageDescription(stageCode) {
    if (stageCode === undefined || stageCode === null) {
        return '未知状态';
    }
    
    // 将可能的字符串转换为数字
    const code = Number(stageCode);
    
    switch (code) {
        case 0:
            return '已创建';
        case 1:
            return '正在加工';
        case 2:
            return '质检完成';
        case 3:
            return '正在运输';
        case 4:
            return '已售出';
        default:
            return `未知状态(${code})`;
    }
}

/**
 * 更新加工信息
 */
function updateProcessingInfo() {
    const batchIdHex = document.getElementById('updateBatchId').value;
    const processingInfo = document.getElementById('processingInfo').value;
    
    if (!batchIdHex || !processingInfo) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'alert alert-info fixed-message';
    loadingMessage.innerHTML = '<strong>处理中</strong><p>正在更新加工信息...</p>';
    loadingMessage.style.position = 'fixed';
    loadingMessage.style.top = '20px';
    loadingMessage.style.right = '20px';
    loadingMessage.style.zIndex = '9999';
    loadingMessage.style.maxWidth = '400px';
    loadingMessage.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    
    document.body.appendChild(loadingMessage);
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _processingData: processingInfo
    };
    
    fetch(`${API_BASE_URL}/update-processing`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 处理结果
        if (result.code === '0') {
            showMessage('加工信息更新成功', true);
        } else {
            let errorMsg = result.message || '未知错误';
            
            // 检查是否包含错误信息
            if (result.data && result.data.receiptMessages) {
                errorMsg = result.data.receiptMessages;
                
                // 特殊处理"Require processing completed"错误
                if (errorMsg.includes('Require processing completed')) {
                    errorMsg = '需要先完成加工步骤才能进行此操作';
                }
            }
            
            showMessage(`更新失败: ${errorMsg}`, false);
        }
    })
    .catch(error => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误
        showMessage(`发生错误: ${error.message || '未知错误'}`, false);
    });
}

/**
 * 显示流程错误的特殊提示（带阶段信息）
 * @param {Object} result 原始结果对象
 * @param {Number} currentStageCode 当前阶段代码
 */
function showProcessFlowErrorWithStage(result, currentStageCode) {
    // 获取错误消息
    const errorMsg = result.data && (result.data.returnMessage || result.data.receiptMessages) || '流程顺序错误';
    
    // 分析当前阶段和所需阶段
    let requiredStage = currentStageCode + 1; // 默认需要下一个阶段
    
    // 根据错误信息确定所需阶段
    if (errorMsg.includes('Require processing completed')) {
        requiredStage = 1; // 需要完成加工
    } else if (errorMsg.includes('quality') || errorMsg.includes('Quality') || errorMsg.includes('quality check passed')) {
        requiredStage = 2; // 需要完成质检
    } else if (errorMsg.includes('transport') || errorMsg.includes('Transit') || errorMsg.includes('in transporting')) {
        requiredStage = 3; // 需要完成运输
    }
    
    // 定义所有阶段名称
    const stageNames = [
        "已创建", 
        "正在加工", 
        "质检通过", 
        "运输中", 
        "已售出"
    ];
    
    // 所需阶段名称
    const requiredStageName = stageNames[requiredStage] || "下一阶段";
    
    // 创建错误提示内容
    let errorTitle = "前序步骤未完成";
    let errorContent = `<div class="process-error-container">
        <p class="error-description">当前无法执行该操作，因为前序步骤尚未完成。</p>
        <div class="required-status">
            <strong>需要先完成：</strong> <span class="status-badge required-stage">${requiredStageName}</span>
        </div>
        
        <div class="process-flow-diagram">
            <div class="flow-title">茶叶资产处理流程</div>
            <div class="flow-steps">`;
    
    // 为每个阶段创建流程图步骤
    for (let i = 0; i < stageNames.length; i++) {
        let stepClass = "flow-step";
        if (i < currentStageCode) {
            stepClass += " completed";
        } else if (i === currentStageCode) {
            stepClass += " current";
        } else if (i === requiredStage) {
            stepClass += " required";
        } else {
            stepClass += " pending";
        }
        
        errorContent += `
            <div class="${stepClass}">
                <div class="step-number">${i}</div>
                <div class="step-name">${stageNames[i]}</div>
                ${i < stageNames.length - 1 ? '<div class="step-arrow">→</div>' : ''}
            </div>`;
    }
    
    errorContent += `
            </div>
        </div>
        
        <div class="error-suggestion">
            <strong>下一步操作：</strong>
            <ul>`;
            
    // 根据所需阶段提供建议
    if (requiredStage === 1) {
        errorContent += `
                <li>请先完成茶叶加工步骤</li>
                <li>点击"更新加工信息"按钮并填写必要信息</li>`;
    } else if (requiredStage === 2) {
        errorContent += `
                <li>请先完成质量检验步骤</li>
                <li>点击"提交质量报告"按钮并提供检验结果</li>`;
    } else if (requiredStage === 3) {
        errorContent += `
                <li>请先完成运输步骤</li>
                <li>点击"开始运输"按钮并提供运输方信息</li>`;
    }
    
    errorContent += `
            </ul>
        </div>
    </div>`;
    
    // 添加内联CSS样式
    const customStyle = `
    <style>
        .process-error-container {
            font-family: Arial, sans-serif;
            color: #333;
            padding: 10px;
            text-align: left;
        }
        .error-description {
            margin-bottom: 15px;
            font-size: 14px;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 5px;
        }
        .required-stage {
            background-color: #ffebee;
            color: #c62828;
            animation: pulse 1.5s infinite;
        }
        .required-status {
            margin-bottom: 15px;
            font-size: 16px;
        }
        .process-flow-diagram {
            margin: 20px 0;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            background-color: #f9f9f9;
        }
        .flow-title {
            text-align: center;
            font-weight: bold;
            margin-bottom: 15px;
            color: #546e7a;
        }
        .flow-steps {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        .flow-step {
            display: flex;
            align-items: center;
            margin: 5px 0;
        }
        .step-number {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: #e0e0e0;
            color: #757575;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: bold;
            font-size: 12px;
            margin-right: 5px;
        }
        .step-name {
            font-size: 12px;
            color: #757575;
        }
        .step-arrow {
            margin: 0 8px;
            color: #bdbdbd;
        }
        .flow-step.completed .step-number {
            background-color: #a5d6a7;
            color: #2e7d32;
        }
        .flow-step.completed .step-name {
            color: #2e7d32;
        }
        .flow-step.current .step-number {
            background-color: #90caf9;
            color: #1565c0;
            border: 2px solid #1565c0;
        }
        .flow-step.current .step-name {
            color: #1565c0;
            font-weight: bold;
        }
        .flow-step.required .step-number {
            background-color: #ef9a9a;
            color: #c62828;
            border: 2px solid #c62828;
            animation: pulse 1.5s infinite;
        }
        .flow-step.required .step-name {
            color: #c62828;
            font-weight: bold;
        }
        .error-suggestion {
            margin-top: 15px;
            background-color: #e3f2fd;
            padding: 10px;
            border-radius: 4px;
            font-size: 13px;
        }
        .error-suggestion ul {
            margin: 5px 0 0 20px;
            padding: 0;
        }
        .error-suggestion li {
            margin-bottom: 5px;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
    </style>`;
    
    // 显示SweetAlert2对话框
    Swal.fire({
        title: errorTitle,
        html: customStyle + errorContent,
        icon: 'warning',
        confirmButtonText: '我知道了',
        confirmButtonColor: '#3085d6',
        width: '600px'
    });
}

/**
 * 提交质量报告
 */
function submitQualityReport() {
    const batchIdHex = document.getElementById('qualityBatchId').value;
    const qualityReport = document.getElementById('qualityReport').value;
    
    if (!batchIdHex || !qualityReport) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'alert alert-info fixed-message';
    loadingMessage.innerHTML = '<strong>处理中</strong><p>正在提交质量报告...</p>';
    loadingMessage.style.position = 'fixed';
    loadingMessage.style.top = '20px';
    loadingMessage.style.right = '20px';
    loadingMessage.style.zIndex = '9999';
    loadingMessage.style.maxWidth = '400px';
    loadingMessage.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    
    document.body.appendChild(loadingMessage);
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _reportHash: qualityReport
    };
    
    fetch(`${API_BASE_URL}/submit-quality`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 处理结果
        if (result.code === '0' && (!result.data || !result.data.returnCode)) {
            showMessage('质量报告提交成功', true);
        } else {
            // 检查是否是前序阶段未完成错误
            if (result.data && 
                ((result.data.returnMessage && result.data.returnMessage.includes("Require processing completed")) || 
                (result.data.receiptMessages && result.data.receiptMessages.includes("Require processing completed")))) {
                // 展示流程错误对话框
                showProcessFlowErrorWithStage(result, result.data.stageCode);
            } else {
                // 显示普通错误消息
                let errorMsg = '未知错误';
                if (result.data && result.data.receiptMessages) {
                    errorMsg = result.data.receiptMessages;
                } else if (result.message) {
                    errorMsg = result.message;
                }
                
                showMessage(`提交失败: ${errorMsg}`, false);
            }
        }
    })
    .catch(error => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误
        showMessage(`发生错误: ${error.message || '未知错误'}`, false);
    });
}

/**
 * 开始运输
 */
function startTransporting() {
    const batchIdHex = document.getElementById('transportBatchId').value;
    const carrier = document.getElementById('carrier').value;
    
    if (!batchIdHex || !carrier) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'alert alert-info fixed-message';
    loadingMessage.innerHTML = '<strong>处理中</strong><p>正在启动运输流程...</p>';
    loadingMessage.style.position = 'fixed';
    loadingMessage.style.top = '20px';
    loadingMessage.style.right = '20px';
    loadingMessage.style.zIndex = '9999';
    loadingMessage.style.maxWidth = '400px';
    loadingMessage.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    
    document.body.appendChild(loadingMessage);
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _transporter: carrier
    };
    
    fetch(`${API_BASE_URL}/start-transporting`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 处理结果
        if (result.code === '0' && (!result.data || !result.data.returnCode)) {
            showMessage('开始运输成功', true);
        } else {
            // 检查是否是前序阶段未完成错误
            if (result.data && 
                ((result.data.returnMessage && result.data.returnMessage.includes("quality inspection")) || 
                 (result.data.receiptMessages && result.data.receiptMessages.includes("quality inspection")) ||
                 (result.data.returnCode == 22))) {
                // 展示流程错误对话框
                showProcessFlowErrorWithStage(result, result.data.stageCode);
            } else {
                // 显示普通错误消息
                let errorMsg = '未知错误';
                if (result.data && result.data.receiptMessages) {
                    errorMsg = result.data.receiptMessages;
                } else if (result.message) {
                    errorMsg = result.message;
                }
                
                showMessage(`启动运输失败: ${errorMsg}`, false);
            }
        }
    })
    .catch(error => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误
        showMessage(`发生错误: ${error.message || '未知错误'}`, false);
    });
}

/**
 * 标记为已售出
 */
function markAsSold() {
    const batchIdHex = document.getElementById('soldBatchId').value;
    const buyer = document.getElementById('buyer').value;
    
    if (!batchIdHex || !buyer) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'alert alert-info fixed-message';
    loadingMessage.innerHTML = '<strong>处理中</strong><p>正在标记资产为已售出...</p>';
    loadingMessage.style.position = 'fixed';
    loadingMessage.style.top = '20px';
    loadingMessage.style.right = '20px';
    loadingMessage.style.zIndex = '9999';
    loadingMessage.style.maxWidth = '400px';
    loadingMessage.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    
    document.body.appendChild(loadingMessage);
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _buyer: buyer
    };
    
    fetch(`${API_BASE_URL}/mark-sold`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 处理结果
        if (result.code === '0' && (!result.data || !result.data.returnCode)) {
            showMessage('茶叶资产已成功标记为已售出', true);
        } else {
            // 检查是否是前序阶段未完成错误
            if (result.data && 
                ((result.data.returnMessage && result.data.returnMessage.includes("Ownership transferred")) || 
                (result.data.receiptMessages && result.data.receiptMessages.includes("Ownership transferred")) ||
                (result.data.returnCode == 22))) {
                // 展示流程错误对话框
                showProcessFlowErrorWithStage(result, result.data.stageCode);
            } else {
                // 显示普通错误消息
                let errorMsg = '未知错误';
                if (result.data && result.data.receiptMessages) {
                    errorMsg = result.data.receiptMessages;
                } else if (result.message) {
                    errorMsg = result.message;
                }
                
                showMessage(`操作失败: ${errorMsg}`, false);
            }
        }
    })
    .catch(error => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误
        showMessage(`发生错误: ${error.message || '未知错误'}`, false);
    });
}

/**
 * 转移所有权
 */
function transferOwnership() {
    const batchIdHex = document.getElementById('transferBatchId').value;
    const newOwner = document.getElementById('newOwner').value;
    
    if (!batchIdHex || !newOwner) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'alert alert-info fixed-message';
    loadingMessage.innerHTML = '<strong>处理中</strong><p>正在转移资产所有权...</p>';
    loadingMessage.style.position = 'fixed';
    loadingMessage.style.top = '20px';
    loadingMessage.style.right = '20px';
    loadingMessage.style.zIndex = '9999';
    loadingMessage.style.maxWidth = '400px';
    loadingMessage.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    
    document.body.appendChild(loadingMessage);
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _newOwner: newOwner
    };
    
    fetch(`${API_BASE_URL}/transfer-ownership`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 处理结果
        if (result.code === '0') {
            showMessage('资产所有权转移成功', true);
        } else {
            let errorMsg = result.message || '未知错误';
            
            // 检查是否包含错误信息
            if (result.data && result.data.receiptMessages) {
                errorMsg = result.data.receiptMessages;
            }
            
            showMessage(`转移失败: ${errorMsg}`, false);
        }
    })
    .catch(error => {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误
        showMessage(`发生错误: ${error.message || '未知错误'}`, false);
    });
}

// 复制批次ID到所有输入框
function copyBatchIdToAll(batchId) {
    document.getElementById('queryBatchId').value = batchId;
    document.getElementById('updateBatchId').value = batchId;
    document.getElementById('qualityBatchId').value = batchId;
    document.getElementById('transportBatchId').value = batchId;
    document.getElementById('soldBatchId').value = batchId;
    document.getElementById('transferBatchId').value = batchId;
    
    // 显示成功消息
    showMessage('批次ID已复制到所有输入框', true);
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 生成随机批次ID
    const randomBatchId = '0x' + [...Array(64)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
    document.getElementById('batchId').value = randomBatchId;
    
    // 设置示例茶叶类型和产地
    document.getElementById('teaType').value = '龙井';
    document.getElementById('origin').value = '杭州西湖';
    
    // 添加批次ID复制按钮事件监听
    document.getElementById('copyBatchIdBtn').addEventListener('click', function() {
        const currentBatchId = document.getElementById('batchId').value;
        copyBatchIdToAll(currentBatchId);
    });
}); 

/**
 * 完成销售流程
 */
function finalizeSale() {
    const batchIdHex = document.getElementById('saleBatchId').value;
    const salePrice = document.getElementById('salePrice').value;
    const buyer = document.getElementById('buyer').value;
    
    if (!batchIdHex || !salePrice || !buyer) {
        showMessage('错误: 所有字段都是必填的!', false);
        return;
    }
    
    // 显示临时加载消息
    Swal.fire({
        title: '处理中',
        text: '正在提交销售记录...',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        willOpen: () => {
            Swal.showLoading();
        }
    });
    
    const batchId = formatBatchIdToBase64(batchIdHex);
    
    const data = {
        _batchId: batchId,
        _salePrice: salePrice,
        _buyer: buyer
    };
    
    fetch(`${API_BASE_URL}/finalize-sale`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        Swal.close();
        
        if (result.code === '0' && (!result.data || !result.data.returnCode)) {
            // 销售成功
            Swal.fire({
                title: '成功',
                text: '销售记录已成功提交',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });
        } else {
            // 检查是否是前序阶段未完成错误
            if (result.data && 
                ((result.data.returnMessage && result.data.returnMessage.includes("transporting")) || 
                (result.data.receiptMessages && result.data.receiptMessages.includes("transporting")))) {
                // 展示流程错误对话框
                showProcessFlowErrorWithStage(result, result.data.stageCode);
            } else {
                // 显示普通错误消息
                let errorMsg = '未知错误';
                if (result.data && result.data.receiptMessages) {
                    errorMsg = result.data.receiptMessages;
                } else if (result.message) {
                    errorMsg = result.message;
                }
                
                Swal.fire({
                    title: '错误',
                    text: `销售记录提交失败: ${errorMsg}`,
                    icon: 'error'
                });
            }
        }
    })
    .catch(error => {
        Swal.close();
        
        // 显示错误
        Swal.fire({
            title: '错误',
            text: `发生错误: ${error.message || '未知错误'}`,
            icon: 'error'
        });
    });
}

/**
 * 获取茶叶资产的完整状态时间线
 */
function getTeaStageTimeline() {
    const batchId = document.getElementById('timelineBatchId').value.trim();
    if (!batchId) {
        Swal.fire({
            icon: 'warning',
            title: '请输入批次ID',
            timer: 2000,
            showConfirmButton: false
        });
        return;
    }

    // 显示加载中
    Swal.fire({
        title: '加载中...',
        allowOutsideClick: false,
        allowEscapeKey: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    // 调用后端API获取时间线数据
    fetch('/tea/asset/timeline/' + batchId)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.json();
        })
        .then(data => {
            Swal.close();
            
            if (data.code !== 200) {
                Swal.fire({
                    icon: 'error',
                    title: '获取时间线失败',
                    text: data.message || '未知错误',
                    timer: 2000,
                    showConfirmButton: false
                });
                return;
            }
            
            // 成功获取到时间线数据
            Swal.fire({
                icon: 'success',
                title: '获取时间线成功',
                timer: 1500,
                showConfirmButton: false
            });
            
            // 渲染时间线
            renderTimeline(data.data);
        })
        .catch(error => {
            console.error('获取时间线失败:', error);
            Swal.fire({
                icon: 'error',
                title: '获取时间线失败',
                text: error.message || '未知错误',
                timer: 2000,
                showConfirmButton: false
            });
        });
}

/**
 * 渲染时间线
 * @param {Array} timelineData 时间线数据
 */
function renderTimeline(timelineData) {
    const timelineContainer = document.getElementById('timelineContainer');
    timelineContainer.innerHTML = '';
    
    if (!timelineData || timelineData.length === 0) {
        timelineContainer.innerHTML = '<div class="alert alert-info">暂无时间线数据</div>';
        timelineContainer.style.display = 'block';
        return;
    }
    
    // 创建时间线HTML
    const timelineHtml = document.createElement('div');
    timelineHtml.className = 'timeline-container';
    
    // 添加时间线CSS
    const timelineStyle = document.createElement('style');
    timelineStyle.textContent = `
        .timeline-container {
            position: relative;
            padding: 20px 0;
        }
        .timeline-container::before {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: 20px;
            width: 4px;
            background: #ccc;
        }
        .timeline-item {
            position: relative;
            margin-bottom: 30px;
            padding-left: 60px;
        }
        .timeline-item .timeline-badge {
            position: absolute;
            left: 10px;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: #4CAF50;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            z-index: 1;
        }
        .timeline-item .timeline-content {
            padding: 15px;
            background: #f9f9f9;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .timeline-item .timeline-date {
            color: #777;
            font-size: 0.85em;
            margin-bottom: 5px;
        }
        .timeline-item .timeline-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
    `;
    timelineContainer.appendChild(timelineStyle);
    
    // 添加时间线项目
    timelineData.forEach((item, index) => {
        const timelineItem = document.createElement('div');
        timelineItem.className = 'timeline-item';
        
        // 添加徽章
        const badge = document.createElement('div');
        badge.className = 'timeline-badge';
        badge.textContent = index + 1;
        timelineItem.appendChild(badge);
        
        // 添加内容
        const content = document.createElement('div');
        content.className = 'timeline-content';
        
        const date = document.createElement('div');
        date.className = 'timeline-date';
        date.textContent = formatDate(item.timestamp);
        content.appendChild(date);
        
        const title = document.createElement('div');
        title.className = 'timeline-title';
        title.textContent = getStageDescription(item.stage);
        content.appendChild(title);
        
        const description = document.createElement('div');
        description.className = 'timeline-description';
        description.textContent = item.description || '无详细描述';
        content.appendChild(description);
        
        timelineItem.appendChild(content);
        timelineHtml.appendChild(timelineItem);
    });
    
    timelineContainer.appendChild(timelineHtml);
    timelineContainer.style.display = 'block';
}

/**
 * 格式化日期
 * @param {number} timestamp 时间戳
 * @return {string} 格式化后的日期字符串
 */
function formatDate(timestamp) {
    if (!timestamp) return '未知时间';
    
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 显示流程错误的特殊提示（兼容旧接口）
 * @param {Object} result 原始结果对象
 */
function showProcessFlowError(result) {
    // 确定错误类型和估算当前阶段
    const errorMsg = result.data && (result.data.returnMessage || result.data.receiptMessages) || '';
    let currentStage = 0;
    
    // 根据错误信息估算当前阶段
    if (errorMsg.includes('quality inspection')) {
        currentStage = 1; // 当前在"加工"阶段
    } else if (errorMsg.includes('transporting') || errorMsg.includes('Ownership transferred')) {
        currentStage = 2; // 当前在"质检"阶段
    }
    
    // 如果返回数据中包含实际阶段信息，则使用
    if (result.data && typeof result.data.stageCode !== 'undefined') {
        currentStage = parseInt(result.data.stageCode);
    }
    
    // 调用新的带阶段信息的流程错误显示函数
    showProcessFlowErrorWithStage(result, currentStage);
} 